interface TreeNode {
  classifyName: string
  children?: TreeNode[]
  total: number
  ratio: number
}

interface ILink {
  source: string
  target: string
  value: number
  ratio: number
}
interface IData {
  name: string
  ratio: number
}

interface Result {
  links: ILink[]
  data: IData[]
}

export function traverseTree(node: TreeNode, nameSet: Set<string> = new Set()): Result {
  let links: ILink[] = []
  let data: IData[] = []
  // 过滤掉占比小于0.5%的能耗节点
  if (node.ratio > 0.005) {
    if (!nameSet.has(node.classifyName)) {
      data.push({ name: node.classifyName, ratio: node.ratio })
      nameSet.add(node.classifyName)
    }
    if (node.children && node.children.length > 0) {
      node.children = node.children.sort((a,b) => a.sort - b.sort)
      for (const child of node.children) {
        if (node.classifyName != child.classifyName) {
          links.push({
            source: node.classifyName,
            target: child.classifyName,
            // source: `${node.classifyName}-${node.ratio}`,
            // target: `${child.classifyName}-${child.ratio}`,
            value: child.total || 0,
            ratio: child.ratio,
          })
        }
        const childResult = traverseTree(child, nameSet)

        links = links.concat(childResult.links)
        data = data.concat(childResult.data)
      }
    }
  }
  return { links, data }
}

// const tree: TreeNode = {
//   classifyName: 'A',
//   children: [
//     {
//       classifyName: 'B',
//       children: [
//         { classifyName: 'C', total: 14, ratio: 0.11 },
//         { classifyName: 'D', total: 12, ratio: 0.12 },
//       ],
//       total: 10,
//       ratio: 0.5,
//     },
//     {
//       classifyName: 'E',
//       children: [
//         {
//           classifyName: 'F',
//           total: 34,
//           ratio: 0.07,
//           children: [{ classifyName: 'G', total: 9, ratio: 0.2 }],
//         },
//       ],
//       total: 40,
//       ratio: 0.09,
//     },
//   ],
//   total: 20,
//   ratio: 0.6,
// }

// const result = traverseTree(tree)
// console.log(result)
